package cn.wolfcode.service.impl;

import cn.wolfcode.entity.Strategy;
import cn.wolfcode.entity.StrategyCatalog;
import cn.wolfcode.mapper.StrategyCatalogMapper;
import cn.wolfcode.service.IStrategyCatalogService;
import cn.wolfcode.service.IStrategyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author c1eye
 * @since 2022-11-03
 */
@Service
public class StrategyCatalogServiceImpl extends ServiceImpl<StrategyCatalogMapper, StrategyCatalog> implements IStrategyCatalogService {

    @Autowired
    IStrategyService strategyService;

    @Override
    public List<StrategyCatalog> queryByDestId(int destId) {
        QueryWrapper<StrategyCatalog> wrapper = new QueryWrapper<>();
        wrapper.eq("dest_id", destId);
        List<StrategyCatalog> list = list(wrapper);
        for (StrategyCatalog strategyCatalog : list) {
            QueryWrapper<Strategy> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("catalog_id", strategyCatalog.getId());
            List<Strategy> strategies = strategyService.list(queryWrapper);
            strategyCatalog.setStrategies(strategies);
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> queryGroupCatalog() {
        QueryWrapper<StrategyCatalog> wrapper = new QueryWrapper<>();
        wrapper.groupBy("dest_name").select("dest_name destname,GROUP_CONCAT(name) names,GROUP_CONCAT(id) ids");
        List<Map<String, Object>> list = listMaps(wrapper);
        ArrayList<Map<String, Object>> res = new ArrayList<>();
        for (Map<String, Object> map : list) {
            String destname = map.get("destname").toString();
            String nameStr = map.get("names").toString();
            String idStr = map.get("ids").toString();
            String[] names = nameStr.split(",");
            String[] ids = idStr.split(",");
            ArrayList<StrategyCatalog> catalogs = new ArrayList<>();
            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                Long id = Long.parseLong(ids[i]);
                StrategyCatalog strategyCatalog = new StrategyCatalog();
                strategyCatalog.setId(id);
                strategyCatalog.setName(name);
                catalogs.add(strategyCatalog);
            }
            Map<String, Object> catalogMap = new HashMap<>();
            catalogMap.put("destName", destname);
            catalogMap.put("catalogList", catalogs);
            res.add(catalogMap);
        }
        return res;
    }
}
